import store from "@/store";

function removeEl(el) {
  if (el.dataset.oldDisplay === undefined) {
    const display = el.style.display;
    if (display && display != "") {
      el.dataset.oldDisplay = display;
    }
    el.style.display = "none";
  }
}

function displayEl(el) {
  if (el.dataset.oldDisplay !== undefined) {
    el.style.display = el.dataset.oldDisplay;
    delete el.dataset.oldDisplay;
  } else {
    el.style.removeProperty("display");
  }
}

// v-hasPermissions="system:user:add,system:user:query"
function checkPermission(el, binding) {
  const { value } = binding;
  // console.log(value);
  const all_permission = "*:*:*";
  const permissions = store.getters?.permissions;
  if (value && value instanceof Array && value.length > 0) {
    const hasPermissions = permissions?.some((permission) => {
      return all_permission == permission || value.includes(permission);
    });
    if (!hasPermissions) {
      // 移除掉当前的element
      removeEl(el);
    } else {
      displayEl(el);
    }
  } else {
    throw new Error(`请设置操作权限标签值`);
  }
}

function checkRole(el, binding) {
  const { value } = binding;
  // const all_permission = "admin";
  const roles = store.getters?.roles;
  if (value && value instanceof Array && value.length > 0) {
    // console.log(value);
    // console.log("p--" + permissions);
    const hasRoles = roles?.some((role) => {
      return value.includes(role);
    });
    if (!hasRoles) {
      // 移除掉当前的element
      removeEl(el);
    } else {
      displayEl(el);
    }
  } else {
    throw new Error(`请设置操作权限标签值`);
  }
}

export default {
  hasPermission: {
    mounted(el, binding) {
      checkPermission(el, binding);
      // 动态监听权限
      const unwatch = store.watch(
        (state) => state.user.permissions,
        () => checkPermission(el, binding)
      );
      el._unwatchPermission = unwatch;
    },
    updated(el, binding) {
      checkPermission(el, binding);
    },
    beforeUnmount(el) {
      if (el._unwatchPermission) {
        el._unwatchPermission();
        delete el._unwatchPermission;
      }
    },
  },
  hasRole: {
    mounted(el, binding) {
      checkRole(el, binding);
      const unwatch = store.watch(
        (state) => state.user.roles,
        () => checkRole(el, binding)
      );
      el._unwatchRole = unwatch;
    },
    updated(el, binding) {
      checkRole(el, binding);
    },
    beforeUnmount(el) {
      if (el._unwatchPermission) {
        el._unwatchPermission();
        delete el._unwatchPermission;
      }
    },
  },
};
